package com.fly.office.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

public class ExcelTplHandler {

    public static void export(String template, Map map , List list, String fileName, HttpServletResponse response){
        try{
            ServletOutputStream bos1;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(bos).withTemplate(template).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(map, writeSheet);
            excelWriter.fill(list, writeSheet);
            excelWriter.finish();
            String codedFilename = "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", codedFilename);
            bos1 = response.getOutputStream();
            bos1.write(bos.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String convertTemplatePath(String path) {

        ClassPathResource resource = new ClassPathResource(path);
        FileOutputStream fileOutputStream = null;
        // 将模版文件写入到 tomcat临时目录
        String folder = System.getProperty("catalina.home");
        File tempFile = new File(folder + File.separator + path);
        // System.out.println("文件路径：" + tempFile.getPath());
        // 文件存在时 不再写入
        if (tempFile.exists()) {
            return tempFile.getPath();
        }
        File parentFile = tempFile.getParentFile();
        // 判断父文件夹是否存在
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(resource.getInputStream());
            fileOutputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return tempFile.getPath();
    }

}
